<template>
  <div class="app-container">
    <el-button  type="success"  v-permission="'permission.add'" @click="
              () => {
                ;(dialogMenuVisible = true), (menu.pid = 0),(menu.type = 1),(MenuTypeDisabled = true),(dialogFormValue = '添加菜单')
              }
            ">
      添加一级菜单
    </el-button>
    <el-table
      :data="menuList"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
      border
      :tree-props="{ children: 'children', hasChildren: 'hasCn' }"
      :highlight-current-row="true"
    >
      <el-table-column
        prop="name"
        label="名称"
        width="220"
      ></el-table-column>
      <el-table-column label="类型" align="center" width="80">
          <template #default="scope">
            <el-tag
              v-if="scope.row.type === 1"
              type="warning"
              >目录</el-tag
            >
            <el-tag v-if="scope.row.type === 2" type="success"
              >菜单</el-tag
            >
            <el-tag v-if="scope.row.type === 3" type="primary"
              >按钮</el-tag
            >
          </template>
        </el-table-column>
      <el-table-column
        prop="path"
        label="访问路径"
        width="180"
      ></el-table-column>
      <el-table-column prop="permissionValue" label="权限值"></el-table-column>
      <el-table-column label="排序" align="center" width="80" prop="sort" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
            v-if="row.type == 1 || row.type == 2"
            v-permission="'permission.add'"
            round
            plain
            type="success"
            size="small"
            @click="
             openAddDialog(row.id)
            "
          >
            添加
          </el-button>
          <el-button
            v-permission="'permission.update'"
            type="primary"
            size="small"
            @click="() => getMenuById(row)"
            round
            plain
          >
            修改
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="() => remove(row)"
            v-permission="'permission.remove'"
            round
            plain
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加菜单窗口 -->
    <el-dialog v-model="dialogMenuVisible" :title="dialogFormValue">
      <el-form
        ref="menuRef"
        :model="menu"
        :rules="menuValidateRules"
        label-width="120px"
      >
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="menu.name" />
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="menu.type" :disabled="MenuTypeDisabled">
            <el-radio :label="1" :disabled="menuTypeOneDisable">目录</el-radio>
            <el-radio :label="2">菜单</el-radio>
            <el-radio :label="3">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="访问路径" v-if="menu.type==1||menu.type==2" prop="path">
          <el-input v-model="menu.path"  />
        </el-form-item>
        <el-form-item label="功能权限值" v-if="menu.type==3" prop="permissionValue">
          <el-input v-model="menu.permissionValue" />
        </el-form-item>
        <el-form-item label="排序值" prop="sort">
          <el-input-number
            v-model="menu.sort"
            style="width: 100px"
            controls-position="right"
            :min="0"
            :max="100"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetAndCloseForm(menuRef)">取 消</el-button>
        <el-button type="primary" @click="saveOrUpateMenu(menuRef)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import menuApi from '@/api/acl/menu'
import {
  ElInput,
  ElMessage,
  ElMessageBox,
  ElTable,
  FormInstance,
  FormRules,
} from 'element-plus'

const menuForm = {
  name: '',
  pid: 0,
  path: '',
  permissionValue: '',
  type: 1,
  id: null,
  sort:1,
}
const menuRef = ref<FormInstance>()
const dialogFormValue = ref('添加菜单')
const dialogMenuVisible = ref(false)
const menu = reactive(menuForm)
const MenuTypeDisabled = ref(false) // 菜单类型是否静选
const menuTypeOneDisable = ref(false) // 目录菜单是否静选
const menuList = ref([])
const menuValidateRules = reactive<FormRules>({
  name: [{ required: true, trigger: 'blur', message: '菜单名必须输入' }],
  path: [{ required: true, trigger: 'blur', message: '访问路径必须输入' }],
  permissionValue:[{ required: true, trigger: 'blur', message: '权限值必须输入' }],
  type:[{ required: true, trigger: 'blur', message: '类型必须选择' }],
})

const fetchNodeList = () => {
  menuApi.getNestedTreeList().then(response => {
    menuList.value = response.data
  })
}

const remove = data => {

  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return menuApi.removeById(data.id)
    })
    .then(() => {
      fetchNodeList() // 刷新列表
      ElMessage({
        type: 'success',
        message: '删除成功!',
      })
    })
    .catch(response => {
      // 失败
      if (response === 'cancel') {
        ElMessage({
          type: 'info',
          message: '已取消删除',
        })
      } else {
        ElMessage({
          type: 'error',
          message: '删除失败',
        })
      }
    })
}

// 添加或保存菜单
const saveOrUpateMenu = (ref: FormInstance) => {
  ref.validate(valid => {
    if (valid) {
      if (!menu.id) {
        // 添加
        saveMenu(ref)
      } else {
        // 修改
        updateMenu(menu, ref)
      }
    }
  })
}

// 修改菜单
const updateMenu = (obj, ref: FormInstance) => {
  menuApi.update(obj).then(response => {
    // 关闭并重置表单
    resetAndCloseForm(ref)

    ElMessage({
      type: 'success',
      message: '修改成功',
    })
    // 刷新页面
    fetchNodeList()
  })
}

// 添加菜单
const saveMenu = (ref: FormInstance) => {
  menuApi
    .saveLevelOne(menu)
    .then(response => {
      dialogMenuVisible.value = false
      ElMessage({
        type: 'success',
        message: '添加成功',
      })
      // 重置表单
      resetAndCloseForm(ref)
      // 刷新页面
      fetchNodeList()
    })
    .catch(response => {
      // 重置表单
      resetAndCloseForm(ref)
      ElMessage({
        type: 'error',
        message: '添加失败',
      })
    })
}

// 菜单表单取消
const resetAndCloseForm = (ref: FormInstance) => {
  // 清空表单
  menu.name = undefined
  menu.pid = undefined
  menu.path = undefined
  menu.type = 1
  menu.id = undefined
  menu.permissionValue = undefined
  menu.sort = 1
  // 关闭模态框
  dialogMenuVisible.value = false
}
// 点击添加
const openAddDialog = (rowId)=>{
  dialogMenuVisible.value = true
  menu.pid = rowId
  menu.type = 2
  MenuTypeDisabled.value=false
  menuTypeOneDisable.value= true // 不能选择为目录类型

  dialogFormValue.value = '添加菜单'
}

// 点击修改菜单
const getMenuById = node => {
  menuApi.getPermissionById(node.id).then(response => {
    // menu = {...response.data }
    Object.assign(menu, response.data)
    dialogFormValue.value = '编辑菜单'
    
    // 如果是原来就是目录类型，则禁止修改菜单类型
    if(node.type==1){
      MenuTypeDisabled.value = true
    }else {
      // 否则只能选菜单或者按钮
      MenuTypeDisabled.value = false
      menuTypeOneDisable.value = true
    }
    dialogMenuVisible.value = true
  })
}

fetchNodeList()
</script>

<style>
.el-tree-node__content {
  height: 28px;
  line-height: 28px;
}

.dialog-footer {
  text-align: center;
}
</style>
